import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:my_salary/pages/settings/locale/locale_controller.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class LanguageSettingsPage extends StatefulWidget {
  const LanguageSettingsPage({super.key});

  @override
  State<LanguageSettingsPage> createState() => _LanguageSettingsPageState();
}

class _LanguageSettingsPageState extends State<LanguageSettingsPage> {
  Locale? _tempLocale;

  @override
  void initState() {
    super.initState();
    _tempLocale = context.read<LocaleController>().locale;
  }

  void _saveAndExit() {
    context.read<LocaleController>().changeLocale(_tempLocale);
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.languageSettingsTitle),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                _buildRadioTile(
                  title: l10n.languageSettingsFollowSystem,
                  value: null,
                ),
                _buildRadioTile(
                  title: l10n.languageSettingsEnglish,
                  value: const Locale('en'),
                ),
                _buildRadioTile(
                  title: l10n.languageSettingsChineseSimplified,
                  value: const Locale('zh'),
                ),
                // 如果未来要加更多语言，只需追加这里
              ],
            ),
          ),
          SafeArea(
            minimum: const EdgeInsets.all(16),
            child: ElevatedButton(
              onPressed: _saveAndExit,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
              ),
              child: Text(l10n.commonApply),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRadioTile({required String title, required Locale? value}) {
    return RadioListTile<Locale?>(
      title: Text(title),
      value: value,
      groupValue: _tempLocale,
      onChanged: (val) => setState(() => _tempLocale = val),
    );
  }
}
